<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        .box{
            width: 400px;
            margin: 140px auto;
        }
        .box .input{
            width: 400px;
            display: flex;
            height: 40px;
            /*margin: 200px auto;*/
        }
        .box .input .key{
            width: 338px;
            height: 39px;
            line-height: 50px;
            outline: none;
            border: 1px solid #999;
        }
        .box .input .submit{
            width: 58px;
            height: 41px;
        }
        .box .ul{
            list-style-type: none;
            margin-top: 20px;
            width: 338px;
        }
        .box .ul li{
            padding-left: 10px;
            height: 40px;
            line-height: 40px;
            border: 1px solid #ddd;
        }
    </style>
    <script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
    <div class="box">
        <div class="input">
            <input type="text" id="key" name="key" placeholder="&nbsp&nbsp搜索商品" class="key">
            <input type="button" id="submit" class="submit" name="submit" value="搜索">
        </div>
        <div>
            <ul id="ul" class="ul">
            </ul>
        </div>
    </div>

    <script>
        $(document).ready(function (){
            $("#key").on("input",function (){
                if(!$(this).val()){
                    $("#ul").empty();
                    return;
                }
                $.ajax({
                    type:"post",
                    url:"/searchKey",
                    data:{
                        "key":$(this).val()
                    },
                    success:function (data){
                        let list = data;
                        $("#ul").empty();
                        let n = 10>list.length? list.length:10
                        for (let i = 0;i<n;i++) {
                            var newItem = $("<li></li>").text(list[i]);
                            $("#ul").append(newItem);
                        }
                    }
                })
            })
        })
        $("#ul").on("click", "li", function() {
            let value = $(this).text();
            $("#key").val(value)
            $("#ul").empty();
        });
    </script>
</body>
</html>
